package com.xuexi.mashibing;

/**
 * 第二问：DCL（double check lock）单利到底需不需要volatile
 * 0 new #2 <java/lang/Object>
 * 4 invokespecial #1 <java/lang/Object.<init> : ()V>
 * 7 astore_1
 * <p>
 * 当4-7发生指令重排序时
 */
public class DCL_Volatile {

    private static volatile DCL_Volatile INSTANCE;


    public static DCL_Volatile getInstance() {
        if (INSTANCE == null) {
            synchronized (DCL_Volatile.class) {
                if (INSTANCE == null) {
                    INSTANCE = new DCL_Volatile();
                }
            }
        }
        return INSTANCE;
    }
    private DCL_Volatile(){}

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> System.out.println(DCL_Volatile.getInstance().hashCode())).start();
        }
    }
}
